package com.yhb.demo.controller;

import com.yhb.demo.beans.UserInfo;
import com.yhb.demo.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService service;

    @RequestMapping("/userlist")
    private String userList(Model model){
        List<UserInfo> list=service.getAllUser();
        model.addAttribute("contents", list);
        return "/user/userlist";
    }

    @RequestMapping("/form")
    public String form(Model model){
        model.addAttribute("user", new UserInfo());
        return "/user/form";
    }

    @PostMapping
    public String saveUser(UserInfo user){
        //处理新增和编辑
        //id为0表示新增
        if(user.getId()==0){
            service.insertUser(user.getCardno(), user.getPsname());
        }else{
            service.updateById(user.getId(), user.getCardno(), user.getPsname());
        }

        //客户端重定向跳转，请求的是Controller
        return "redirect:/user/userlist";
        //如果用服务器跳转，写法：forward:/xxxxx

    }
    @GetMapping("{id}")
    public String userview(@PathVariable("id")int id,Model model){
        UserInfo user=service.getUserById(id);
        model.addAttribute("user", user);
        return "/user/userview";
    }
    @GetMapping("edit/{id}")
    public String editForm(@PathVariable("id")int id,Model model) {

        //修改页面需要根据id查询用户信息
        UserInfo user = service.getUserById(id);

        model.addAttribute("user", user);

        return "/user/form";

    }

    @GetMapping("delete/{id}")
    public String delete(@PathVariable("id")int id) {

        service.deleteById(id);

        return "redirect:/user/userlist";

    }
}
